<template>
  <Form ref="formValidate" :model="formValidate" :rules="ruleValidate"
        :label-width="120" style="width: 350px;">
    <FormItem label="推荐渠道" prop="channel">
      <Select v-model="formValidate.channel" placeholder="请选择渠道">
        <Option v-for="(item,index) in channelList" :value="item.channelId">{{item.channelName}}</Option>
      </Select>
    </FormItem>
    <!--<FormItem label="应用类型" prop="type">-->
      <!--<Select v-model="formValidate.type" placeholder="请选择应用类型">-->
        <!--<Option value="01">Web</Option>-->
        <!--<Option value="02">App</Option>-->
        <!--<Option value="03">H5</Option>-->
      <!--</Select>-->
    <!--</FormItem>-->

    <FormItem label="推荐场景名称" prop="name">
      <Input v-model="formValidate.name" placeholder="请输入场景名称"></Input>
    </FormItem>
    <FormItem label="推荐场景ID" prop="ID">
      <Input v-model="formValidate.ID" :disabled="this.isEdit"
             placeholder="推荐场景ID为渠道请求的参数"></Input>
    </FormItem>
    <FormItem label="返回结果数" prop="num">
      <Input v-model="formValidate.num" @on-change="numChange"></Input>
    </FormItem>
    <FormItem label="推荐场景描述" prop="desc">
      <Input v-model="formValidate.desc" type="textarea" :autosize="{minRows: 2,maxRows: 5}"
             placeholder="请输入描述"></Input>
    </FormItem>
    <FormItem label="推荐类型" prop="recommendType" style="position:relative">
      <Select v-model="formValidate.recommendType" placeholder="请选择推荐类型" @on-change="typeChange">
        <Option v-for="(item,index) in recommendTypeList" :value="item.id">{{item.queryName}}</Option>
      </Select>
       <Checkbox v-model="formValidate.proAttrIden" style="position:absolute;left:237px;top:0;width:74px">返回标签</Checkbox>
    </FormItem>
<template v-if="formValidate.recommendType == '003'&&formValidate.proList.length" >
    <FormItem v-for="(itemP,index) in formValidate.proList" label="" prop="" style="width: 377px;margin-left:-35px">
      <span style="margin-right:5px;border:solid 1px #ccc;padding:5px 8px">{{index+1}}</span>
      <Select  v-model="itemP.proType"
      	:label-in-value="true" 
      	 @on-change="v=>{productTypeChange(v,index)}"
              style="width: 110px" placeholder="指定产品类型">
        <Option v-for="item in productTypeList" :value="item.proTypeId" :key="item.proTypeId">{{ item.proTypeName }}</Option>
      </Select>
      <Select v-model="itemP.proId"
      filterable
      style="width: 110px" placeholder="指定产品ID"
      	:label-in-value="true"      
      >
        <Option v-for="(item,index) in productList" :disabled="JSON.stringify(formValidate.proList).indexOf(item.proId)>-1"
         :value="item.proId">{{item.proId}}</Option>
      </Select>
      <span style="margin-left: 10px;color: #cccccc">指定产品个数必须与返回结果数一致！</span>
    </FormItem>
 </template> 
    <FormItem v-if="formValidate.recommendType == '001'" label="推荐规则选择" prop="" >
      <Select v-model="recommendRule" filterable multiple  @on-change="noMoreFive"
              placeholder="请选择推荐规则">
        <Option v-for="(item,index) in groupList" :value="item.regulationId">{{item.reguName}}</Option>
      </Select>
      <span style="color: #ccc;margin-left: 10px;">推荐规则最多只能选择5个</span>
    </FormItem>

    <FormItem v-if="formValidate.recommendType == '002'" label="算法选择" prop="">
      <Select v-model="recommendAlgorithm" placeholder="请选择算法">
        <Option v-for="(item,index) in algorithmList" :value="item.algorithmId">{{item.algorithmName}}</Option>
      </Select>
    </FormItem>


    <FormItem style="margin-bottom: 0;text-align: center;">
      <Button type="primary" @click="handleSubmit('formValidate')" style="margin-right: 40px;">保存</Button>
      <Button type="ghost" @click="handleReset('formValidate')" style="margin-left: 8px;color:#666">重置</Button>
    </FormItem>
  </Form>
</template>

<script>
  import {PROTYPES} from '../../utils/common'

  export default{
    data: function () {
      return {
        proList:{},
        algorithmId:'',
        isEdit:false,
        // proAttrIden: false,
        channelList:[],
        recommendTypeList:[],
        algorithmList:[],
        groupList:[],
        productList:[],
        productTypeList:PROTYPES,
        recommendRule:'',
        productId:'',
        productType:'01',
        recommendAlgorithm:'',

        formValidate: {
          channel:'',
          recommendType:'',
          name: '',
          ID: '',
          num: 0,
          desc: '',
          algorithmId:'',
          proList:[],
          proAttrIden:"false",
          
      },
        ruleValidate: {
          channel: [
            { required: true, message: '请选择推荐渠道', trigger: 'change' }
          ],
//          type: [
//            { required: true, message: '请选择应用类型', trigger: 'change' }
//          ],
          name: [
            { required: true, message: '推荐场景名称不能为空', trigger: 'blur' }
          ],
          ID: [
            { required: true, message: '推荐场景ID不能为空', trigger: 'blur' }
          ],
          num: [
            { required: true, message: '请输入返回结果数', trigger: 'blur' }
          ],
          desc: [
            { required: true, message: '请填写推荐场景描述', trigger: 'blur' },
            //{ type: 'string', min: 20, message: '描述不少于20个字符', trigger: 'blur' }
          ],
          recommendRule:[
            //{ required: true, message: '请填写推荐场景描述', trigger: 'blur' },
            { type: 'array', max: 3, message: '描述不少于20个字符', trigger: 'blur' }
          ],
          recommendType: [
            { required: true, message: '请选择推荐类型', trigger: 'change' }
          ],
        }
      }
    },
    components: {},
    methods: {
      typeChange(val){
          if(this.formValidate.recommendType=="003"){
            this.formValidate.proList=[]
            for(var i=0;i<this.formValidate.num;i++){
                this.formValidate.proList.push({
                  proType:'',
                  proId:'',
                  sort:i-0+1
                })
            }
          }
        },
      getDetails(data){
        this.reset()
        this.formValidate = data;
        // console.log(this.formValidate)
        // var a=this.formValidate;
        // debugger;
        // var b=this.formValidate.algorithmId;
        // var c=JSON.parse(this.formValidate.algorithmId);
        //console.log(JSON.parse(this.formValidate.algorithmId)[0].proId);
        this.isEdit = true;//修改时
        if(data.recommendType == '001'){
          this.recommendRule = data.algorithmId.split(';')
        }else if(data.recommendType == '002'){
          this.recommendAlgorithm = data.algorithmId;

        }else if(data.recommendType == '003'){

        }
      },
      //提交
      handleSubmit (name) {
        let _this = this
        this.$refs[name].validate((valid) => {
          if (valid) {
            if(this.formValidate.recommendType== '001'){
              //客群
              if(this.recommendRule.length>5){
                this.$Message.error('推荐规则最多只能选择5个！');
                return
              }
              this.formValidate.algorithmId = this.recommendRule.join(';')

            }else if(this.formValidate.recommendType == '002'){
              //算法
              this.formValidate.algorithmId = this.recommendAlgorithm
              // console.log(this.formValidate.algorithmId)

            }else if(this.formValidate.recommendType== '003'){
              this.formValidate.algorithmId=''

              //指定产品
          
            }

            if(this.isEdit){
              this.api({
                url: "/scene/update",
                method: "post",
                params:{
                  channelId:this.formValidate.channel,
                  sceneName:this.formValidate.name,
                  sceneId:this.formValidate.ID,
                  sceneResult:this.formValidate.num,
                  sceneDesc:this.formValidate.desc,
                  queryTypeId:this.formValidate.recommendType,
                  algorithmId:this.formValidate.algorithmId,
                  proAttrIden:this.formValidate.proAttrIden?1:0,
                  proList:JSON.stringify({a:this.formValidate.proList})
                }
                //qs.stringify(params)
              }).then(data => {
                // debugger
                _this.$Message.success('修改场景成功！');
                _this.$parent.cancel()
                _this.isEdit = false
                _this.handleReset('formValidate')
                _this.$emit('refreshbizlines')
              })
            }else{
              //获取场景详情
              this.api({
                url: "/scene/detail",
                method: "post",
                params:{
                  id:_this.formValidate.ID
                }
              }).then(data => {
                if(!(data&&data.sceneId)){
                  //id没有重复 ，可以添加

                  this.api({
                    url: "/scene/add",
                    method: "post",
                    params:{
                      channelId:this.formValidate.channel,
                      sceneName:this.formValidate.name,
                      sceneId:this.formValidate.ID,
                      sceneResult:this.formValidate.num,
                      sceneDesc:this.formValidate.desc,
                      queryTypeId:this.formValidate.recommendType,
                      algorithmId:this.formValidate.algorithmId,
                      proAttrIden:this.formValidate.proAttrIden?1:0,
                      proList:JSON.stringify({a:this.formValidate.proList})
                    }
                    //qs.stringify(params)
                  }).then(data => {
                    this.$Message.success('添加场景成功！');
                    this.$parent.cancel()
                    this.handleReset('formValidate')
                    this.$emit('refreshbizlines')
                  })
                }else{
                  return
                }
              }
              )
            }

          } else {
            //this.$Message.error('Fail!');
          }
        })
      },
      handleReset (name) {
        this.$refs[name].resetFields();
      },
      noMoreFive(val){

      },
      numChange(params){
        if(params.data==null){
          return 
        }
        let len = this.formValidate.proList.length
        if(len>params.data){
          //减少结果数
          this.formValidate.proList = this.formValidate.proList.slice(0,params.data-0)
        }else if(this.formValidate.recommendType=="003"){
          let cha  = params.data - len
          for(var i=0;i<cha;i++){
           this.formValidate.proList.push({
             proType:'',
             proId:'',
             sort:len-0+i+1
           })
          }
       
        }
        this.$set(this.formValidate,'proList',this.formValidate.proList)
        // console.log(this.formValidate)
      },
      productTypeChange(val,item){
        debugger
        // console.log(val,"item")
         var proTypeName = val.value
	   // this.productId = []
        this.api({
          url: "/product/list",
          method: "post",
          params:{
            type:val.value
          }
        }).then(data => {
        
          this.productList = data;
        })
      },
      reset(){
        this.isEdit = false
        this.recommendRule='';
        this.productId='';
        this.productType='01';
        this.recommendAlgorithm='';
        this.$refs['formValidate'].resetFields();
        this.formValidate.proList=[],
        this.formValidate.proAttrIden=false;
      }
    },
    created(){
      //推荐渠道列表
      this.api({
        url: "/channel/list",
        method: "post"
      }).then(data => {
        this.channelList = data;
        // console.log(data)

      })

      //推荐类型列表
      this.api({
        url: "/query/type/list",
        method: "post"
      }).then(data => {
        // console.log(data)
        this.recommendTypeList = data;
        
      })

      //算法列表
      this.api({
        url: "/algorithm/list",
        method: "post"
      }).then(data => {
       
        this.algorithmList = data;
        this.algorithmId=data.algorithmId || {}
       
      })

      //细分客群-推荐规则列表
      this.api({
        url: "/regulation/list",
        method: "post"
      }).then(data => {
        //  console.log(data)
        this.groupList = data;
      })
      //指定产品列表
      this.api({
        url: "/product/list",
        method: "post",
        params:{
          type:this.productType
        }
      }).then(data => {
        // console.log(data)
        this.productList = data;
      })

    },

    mounted() {
    },
    

  }
</script>

<style lang="scss" scoped>
element.style {
 margin-left: 100px!important;
}
</style>
